Categories
React Hooks

Top React Hooks — Portal and Flux

Spread the love

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

React Cool Portal

React Cool Portal lets us render our elements outside the usual DOM hierarchy determined by React.

To install it, we run:

yarn add react-cool-portal

or:

npm install --save react-cool-portal

Then we can use it by writing:

import React from "react";
import usePortal from "react-cool-portal";

export default function App() {
  const { Portal } = usePortal();

  return (
    <div>
      <Portal>
        <p>hello world </p>
      </Portal>
    </div>
  );
}

We called the usePortal hook to return the Portal component.

Then we can render our elements inside the Portal .

By default, the elements inside will be attached to the body.

We can add the ID of the container with the containerId .

If the element with the given ID doesn’t exist, it’ll create it for us.

For instance, we can write:

import React from "react";
import usePortal from "react-cool-portal";

export default function App() {
  const { Portal } = usePortal({ containerId: "portal" });

  return (
    <div>
      <Portal>
        <p>hello world </p>
      </Portal>
    </div>
  );
}

It also comes with states that we can use to determine whether we show or hide the element in the portal.

For example, we can write:

import React from "react";
import usePortal from "react-cool-portal";

export default function App() {
  const { Portal, isShow, show, hide, toggle } = usePortal({
    defaultShow: false,
    onShow: e => {
      // ...
    },
    onHide: e => {
      // ...
    }
  });

  return (
    <div>
      <button onClick={show}>Open</button>
      <button onClick={hide}>Close</button>
      <button onClick={toggle}>{isShow ? "Close" : "Open"} Modal</button>
      <Portal>
        <div class="modal" tabIndex={-1}>
          <div>
            <h5>Modal title</h5>
            <p>Modal body.</p>
          </div>
        </div>
      </Portal>
    </div>
  );
}

We used the userPotal hook to get more properties from the returned object.

It returns the show and hide functions to show and hide the portal.

toggle is a function to toggle the portal.

isShow has the state to indicate whether the portal is shown or not.

defaultShow sets whether the portal elements are shown by default or not.

onShow is the function to run something when the portal is shown.

onHide is the function that runs when the portal is hidden.

react-enhanced-reducer-hook

The react-enhanced-reducer-hook library lets us create a centralized data store in our app.

It’s inspired by Redux and works similarly to it.

To install it, we run:

npm install react-enhanced-reducer-hook --save

Then we can use it by writing:

import React from "react";
import useEnhancedReducer from "react-enhanced-reducer-hook";

function logMiddleware({ getState }) {
  return next => action => {
    console.log("Prev State:", getState());
    console.log("Action:", action);
    next(action);
    console.log("Next State:", getState());
  };
}

function useAppReducer(reducer, inititalState) {
  return useEnhancedReducer(reducer, inititalState, [logMiddleware]);
}

function counterReducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    case "reset":
      return { count: 0 };
    default:
      return state;
  }
}

export default function App() {
  const [state, dispatch] = useAppReducer(counterReducer, { count: 0 });
  return (
    <React.Fragment>
      <button onClick={() => dispatch({ type: "increment" })}>increment</button>
      <button onClick={() => dispatch({ type: "decrement" })}>decrement</button>
      <button onClick={() => dispatch({ type: "reset" })}>reset</button>
      <br />
      Count: {state.count}
    </React.Fragment>
  );
}

We have the useAppReducer hook, which we pass the counterReducer into it.

The hook is created by us by using the useEnhancedReducer hook where we pass the reducer, initial state, and any middleware that we want to run into it.

We return the results of useEnhancedReducer so that we can use it in our component.

The Redux reducer is like any other reducer.

We have the logMiddleware that we can run during state changes.

In App , we get the state and dispatch variables.

state has the current state.

And dispatch has the function to dispatch our actions.

The type is the action type.

Then we get the count state with state.count .

Conclusion

React Cool Portal lets us create portals without the hassle.

The react-enhanced-reducer-hook library lets us create a centralized data store.

The library is inspired by Redux.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *